package com.gitee.wsl.ext.array


/**
 * Extends ByteBuf to add a read* method for unsigned varints, as defined in https://github.com/multiformats/unsigned-varint.
 */
@kotlin.ExperimentalUnsignedTypes
fun ByteArray.readUvarint(): Pair<Long, ByteArray>? {
    var x: Long = 0
    var s = 0

    var index = 0
    var result: Long? = null
    for (i in 0..8) {
        val b = this.get(index++).toUByte().toShort()
        if (b < 0x80) {
            result = x or (b.toLong() shl s)
            break
        }
        x = x or (b.toLong() and 0x7f shl s)
        s += 7
    }

    // Check that we didn't break early.
    if (result != null && index <= size) {
        return Pair(result, slice(IntRange(index, size - 1)).toByteArray())
    }

    throw IllegalStateException("uvarint too long")
}
